package com.kobe.tokendemo.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;

import java.io.IOException;
import java.util.Base64;
import java.util.Date;

/**
 * 创建 JYQ  on  2018/11/1,11:39
 */
public class JWTUtils {




    public static String newToken(Long userId){
    /**
     * 默认过期时间三十分钟
     */
    return  newToken(userId,Constants.DEFAULT_EXPIRED_SECONDS);
}

    /**
     *
     * @param  userId
     * @param expiredTime 过期时长
     * @return
     */
    public  static  String  newToken(Long userId,Long expiredTime){
        return JWT.create().withClaim("userId",userId)
                .withIssuedAt(new Date())
                .withExpiresAt(new Date(System.currentTimeMillis()+expiredTime *1000))
                .sign(Algorithm.HMAC256(Constants.SERCRET_KEY));


    }
//    校验token  是否合法
    public static boolean checkToken(String token){

        JWTVerifier build = JWT.require(Algorithm.HMAC256(Constants.SERCRET_KEY))
                .build();
        try {
            build.verify(token);
            return true;
        } catch (JWTVerificationException e) {
            e.printStackTrace();
            return  false;
        }

    }
    /**
     * 刷新token
     * param 原来的token
     * return 新token
     */
    public  static  String refreshToken(String token){
        DecodedJWT j = JWT.decode(token);
        Long userId = j.getClaim("userId").asLong();
        return  newToken(userId);

    }

    public  static  String   autoRequire(String token){
        boolean b = checkToken(token);
        if (b) {

            DecodedJWT decode = JWT.decode(token);
//            计算时间是否超过80%
            Long current=System.currentTimeMillis() / 1000;
            Long start=decode.getClaim("iat").asLong();
            Long exp=decode.getClaim("exp").asLong();
            if ((current-start)*1.0/(exp-start)>0.5){
                return refreshToken(token);
            }else {
                return  token;
            }
        }else {
            throw  new JWTVerificationException("token验证不合法");
        }

    }
    public  static  Long  getUserId(String token){
        DecodedJWT decode = JWT.decode(token);
        Long userId = decode.getClaim("userId").asLong();
        return  userId;

    }




}
